import { login, logout, getInfo, getPhone, getVerify, passwordReset, getUser } from '@/api/user'
import { getToken, setToken, removeToken, getTokenType, setTokenType, removeTokenType, getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { get_current_tenant } from '@/api/tenant'

const state = {
  token: getToken(),
  token_type: getTokenType(),
  refresh_token: getRefreshToken(),
  name: '',
  avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80',
  introduction: '',
  roles: [],
  userInfo: JSON.parse(sessionStorage.getItem('user')) || {},
  tenant_accounts: JSON.parse(localStorage.getItem('tenant_accounts')) || {} // 当前租户以及账套信息
}

const mutations = {
  SET_TOKEN: (state, { token, token_type, refresh_token }) => {
    state.token = token
    state.token_type = token_type
    state.refresh_token = refresh_token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER: (state, user) => {
    Object.keys(user).map(k => {
      state[k] = user[k]
    })
  },
  SET_LOGIN_OUT: (state) => {
    state.token = ''
    state.roles = []
    removeToken()
    removeTokenType()
    removeRefreshToken()
    resetRouter()
    state.userInfo = {}
    sessionStorage.removeItem('user')
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    sessionStorage.setItem('user', JSON.stringify(userInfo))
  },
  SET_TENANT_ACCOUNTS: (state, tenant_accounts) => {
    state.tenant_accounts = tenant_accounts
    localStorage.setItem('tenant_accounts', JSON.stringify(tenant_accounts))
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username } = userInfo
    if (username) {
      userInfo.username = username.trim()
    }
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        commit('SET_TOKEN', {
          token: res.access_token,
          token_type: res.token_type,
          refresh_token: res.refresh_token
        })
        setToken(res.access_token)
        setTokenType(res.token_type)
        setRefreshToken(res.refresh_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        removeTokenType()
        removeRefreshToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      removeTokenType()
      removeRefreshToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)
      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },
  verifyPhone({ commit }, userName) {
    return new Promise((resolve, reject) => {
      getPhone({ username: userName }).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getVerifyCode({ commit }, data) {
    return new Promise((resolve, reject) => {
      getVerify(data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  sendPasswordReset({ commit }, data) {
    return new Promise((resolve, reject) => {
      passwordReset(data).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getUserInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUser().then(res => {
        const { data, data: { roles }} = res
        commit('SET_ROLES', Array.isArray(roles) ? roles.map(item => item.roleId) : ['USER'])
        commit('SET_USER_INFO', data)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setUserTenantAccounts({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_TENANT_ACCOUNTS', data)
      return resolve()
    })
  },
  fetchUserTenantAccounts({ commit }) {
    return new Promise((resolve, reject) => {
      get_current_tenant().then(res => {
        const { selfRegister } = res.data
        commit('SET_TENANT_ACCOUNTS', res.data.tenantId ? res.data : { selfRegister })
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
